package com.zheng.study.company.dao.impl;

import com.zheng.study.base.bean.BaseEnumManager;
import com.zheng.study.base.dao.impl.BaseDaoImpl;
import com.zheng.study.company.dao.PowerDao;
import com.zheng.study.company.entity.Company;
import com.zheng.study.company.entity.Department;
import com.zheng.study.company.entity.Power;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import java.util.List;

/**
 * newFile
 * ============================================================================
 * author : dzw
 * createDate:  2018/8/24 。
 * ============================================================================
 */
@Repository
public class PowerDaoImpl extends BaseDaoImpl<Power, String> implements PowerDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<Power> getLevelPowers(Company company, Department department) {
		Assert.notNull(company, "company is required");
		Assert.notNull(department, "department is required");
		String hql = "from " + Power.class.getName() + " model where model.company = :company and model.department.grade <= :grade and model.state = :state order by model.department.pinYinHead asc";
		return getSession().createQuery(hql).setParameter("company", company).setParameter("grade", department.getGrade()).setParameter("state", BaseEnumManager.StateEnum.Enable).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Power> getRootPowerList(Company company) {
		String hql = "from " + Power.class.getName() + " p where p.company = :company and p.parent is null and p.state = :state order by p.department.pinYinHead asc";
		return getSession().createQuery(hql).setParameter("company", company).setParameter("state", BaseEnumManager.StateEnum.Enable).list();
	}

	@Override
	public boolean checkIsHasChildren(Power power) {
		if(power!=null){
			String hql = "select count(*) from " + Power.class.getName() + " p where p.parent = :parent and p.state = :state";
			return ((Long) getSession().createQuery(hql).setParameter("parent", power).setParameter("state", BaseEnumManager.StateEnum.Enable).uniqueResult()) > 0;
		}
		return false;
	}

}
